#include "dwt.h"

void DWT_Delay_Init(void)
{
    // 使能 DWT
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
    DWT->CYCCNT = 0;                     // 清零
    DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; // 计数器使能
}

void DWT_Delay_us(uint32_t us)
{
    uint32_t cycles = (SystemCoreClock / 1000000) * us;
    uint32_t start = DWT->CYCCNT;
    while ((DWT->CYCCNT - start) < cycles)
        ;
}

void DWT_Delay_ms(uint32_t ms)
{
    while (ms--)
    {
        DWT_Delay_us(1000);
    }
}
